/**
 * Created by zhuyongjie on 2017/10/19.
 */
var dataGridId = "dataList";
var configId = "flowTaskConfig";
var queryParams = new Object();
var editUrl = path + "/flow/addOrEditPage";
$(function () {
    setAjaxLoading();
    var url = path + "/flow/flow-defination-query";

    $('#dataList').datagrid({
        title: "",
        url: url,
        //high:100%,
        rowStyler: function(index,row){
            return 'font-size:10px;';
        },
        fit : true,
        border : true,
        fitColumns : true,
        pagination : false,
        singleSelect : true,
        columns: [
            [
                { field: "id", title: "流程定义ID", align: "left",sortable: false,hidden:true, resizable: true, width: 80  },
                { field: "deploymentId", title: "编码", align: "left", sortable: false, resizable: true, width: 80 ,hidden:true, },
                { field: "name", title:"流程名称",align: "left", sortable: false, resizable: true, width: 150},
                { field: "key", title:"Key",align: "left", sortable: false, resizable: true, width: 150},
                { field: "version", title:"版本号",align: "left", sortable: false, resizable: true, width: 200},
                { field: "resourceName", title:"XML",align: "left", sortable: false, resizable: true, width: 80,hidden:true,},
                { field: "diagramResourceName", title:"图片",align: "left", sortable: false, resizable: true, width: 80,hidden:true,},
            ]
        ],
    });
    // $('#dataList').datagrid('options').url = url;
    $("#dataList").datagrid({
        
        onSelect:function (index, row) {
            initFlowConfig(row);
        },
        onLoadSuccess:function(data){
            if (data.total > 0) {
                $("#dataList").datagrid('selectRow', 0);
            }
        }
    });
    resizeDataGridSize(dataGridId,0.3);
    autoResizeDataGrid(dataGridId,0.3);
});

/**
 * 加载流程环节配置数据
 * @param row
 */
function initFlowConfig(row){
    if(row){
        var processKey = row.key;
        var url = path + "/flow/" + processKey +"/listFlowConfig";
        var grid = $("#flowTaskConfig");
        queryParams.processKey = processKey;

        var toolbar = [{id: 'addBtn', text: '新增', iconCls: 'icon-add', handler: addFlowConfig}
            , {id: 'editBtn', text: '修改', iconCls: 'icon-edit', handler: editFlowConfig}
            , {id: 'deleteBtn', text: '删除', iconCls: 'icon-remove', handler: deleteFlowConfig}
        ];

        initGrid(grid,columns,toolbar);

        // 初始化 DataGrid控件信息
        grid.datagrid({
            //设置为false，否则自动布局无效
            fit:false
        });

        resizeDataGridSize(configId,0.68);
        autoResizeDataGrid(configId,0.68);

        getData(grid,queryParams,url);

    }
}
/**
 * 删除环节配置
 */
function deleteFlowConfig() {
    var row = $('#' + configId).datagrid('getSelected');
    var flowRow = $('#' + dataGridId).datagrid('getSelected');
    if (row) {
        var flowId = row.flowId
        var deleteUrl = path + "/flow/" + flowId + "/deleteFlowTask"
        layer.confirm('确认删除？', {icon: 3, title: '提示'}, function (index) {
            $.ajax({
                type: "POST",
                url: deleteUrl,
                data: {
                    flowId :flowId
                },
                dataType: "json",
                success: function (data) {
                    layer.close(index);
                    var analyMsg = data;
                    if (analyMsg.code != '0000') {
                        $.alert('default', 'info', analyMsg.msg);
                    } else {
                        $.alert('default', 'info', "删除成功");
                        setTimeout("closeLayer()",100);//设置延时，防止IE下出现异常
                        initFlowConfig(flowRow);
                    }
                },
                error: function (data, textstatus) {
                    layer.close(index);
                    layer.alert("删除失败", {closeBtn: 0, shift: 4});
                }
            });

        });
    }else{
        layer.alert("请选择", {closeBtn: 0, shift: 4});
    }
}

/**
 * 修改环节配置
 */
function editFlowConfig() {
    var row = $('#' + configId).datagrid('getSelected');
    var flowRow = $('#' + dataGridId).datagrid('getSelected');
    if (row) {
        openEditWin("edit",row,flowRow);
    }else{
        layer.alert("请选择", {closeBtn: 0, shift: 4});
    }
}

/**
 * 添加环节配置
 */
function addFlowConfig() {
    var row = $('#' + dataGridId).datagrid('getSelected');
    if(row){
        openEditWin("add",row,row);
    }else {
        layer.alert("请选择", {closeBtn: 0, shift: 4});
    }

}


/**
 * 打开窗口
 * @param type
 * @param params
 * @param row
 */
function openEditWin(type,params,row) {
    setGlobalVariable("taskConfigRow",JSON.stringify(params));
    var title = "";
    if(type == "add"){
        title = "添加节点配置";
    }else if(type == "edit"){
        title = "修改节点配置";
    }
    top.layer.open({
        type: 2,
        id: "taskConfig" + Math.random(),//不能有固定id，否则多层次弹窗失败
        title: title,
        area: ['800px','500px'],
        shadeClose: false,
        shade: 0.3,
        maxmin: true,
        content: editUrl + "?type=" + type,
        zIndex: top.layer.zIndex,//重点1,
        success: function (layero) {
            top.layer.setTop(layero); //重点2
        },
        end: function () {
            initFlowConfig(row);
        },
        cancel: function (index) {
            top.layer.close(index);
        }
    });
}

/**
 * 下载流程文件
 */
function downloadFile() {
    var row = $('#' + dataGridId).datagrid('getSelected');
    if (row) {
        var id = row.id;
        var key = row.key;
        var url = path + "/flow/download?id=" + id +"&key=" + key;
        $("#downFrame").attr("src", url);
    }else {
        layer.alert("请选择", {closeBtn: 0, shift: 4});
    }
}

/**
 * 删除流程部署
 */
function deleteDeploy() {
    var row = $('#' + dataGridId).datagrid('getSelected');
    if (row) {
        var deploymentId = row.deploymentId;
        var url = path + "/deploy/" + deploymentId + "/delete";
        layer.confirm('确认删除？', {icon: 3, title: '提示'}, function (index) {
            $.ajax({
                type: "POST",
                url: url,
                data: {},
                dataType: "json",
                success: function (data) {
                    layer.alert("删除成功", {closeBtn: 0, shift: 4});
                    $("#dataList").datagrid("reload");
                    layer.close(index);
                },
                error: function (data, textstatus) {
                    $("#dataList").datagrid("reload");
                    layer.alert("删除失败", {closeBtn: 0, shift: 4});
                    layer.close(index);
                }
            });

        });


    } else {
        layer.alert("请选择", {closeBtn: 0, shift: 4});
    }
}

/**
 * 启动流程
 */
function startInstance() {
    var row = $('#dataList').datagrid('getSelected');
    if (row) {
        var deploymentId = row.deploymentId;
        var url = path + "/process/" + deploymentId + "/startByDeploymentId";
        layer.confirm('确认启动流程？', {icon: 3, title: '提示'}, function (index) {
            $.ajax({
                type: "POST",
                url: url,
                data: JSON.stringify({
                    "audit1": "zhuyongjie"
                }),
               // dataType: "json",
                contentType: 'application/json',
                success: function (data) {
                    layer.alert("启动成功", {closeBtn: 0, shift: 4});
                    $("#dataList").datagrid("reload");
                    layer.close(index);
                },
                error: function (data, textstatus) {
                    $("#dataList").datagrid("reload");
                    layer.alert("启动失败", {closeBtn: 0, shift: 4});
                    layer.close(index);
                }
            });

        });


    } else {
        layer.alert("请选择", {closeBtn: 0, shift: 4});
    }
}
/**
 * 通过Key启动流程
 */
function startInstanceByKey() {
    var row = $('#dataList').datagrid('getSelected');
    if (row) {
        var key = row.key;
        var url = path + "/process/" + key + "/startByKey";
        layer.confirm('确认启动流程？', {icon: 3, title: '提示'}, function (index) {
            $.ajax({
                type: "POST",
                url: url,
                data: JSON.stringify({
                    "audit1": "lisi"
                }),
                // dataType: "json",
                contentType: 'application/json',
                success: function (data) {
                    layer.alert("启动成功", {closeBtn: 0, shift: 4});
                    $("#dataList").datagrid("reload");
                    layer.close(index);
                },
                error: function (data, textstatus) {
                    $("#dataList").datagrid("reload");
                    layer.alert("启动失败", {closeBtn: 0, shift: 4});
                    layer.close(index);
                }
            });

        });


    } else {
        layer.alert("请选择", {closeBtn: 0, shift: 4});
    }
}

var flowUrl = path + "/flow/loadUploadPage";
/**
 * 打开上传界面
 */
function openAddZip() {
    layer.open({
        title:"流程部署",
        type:2,
        area: ['600px','300px'],
        content: flowUrl + "?type=zip",
        maxmin: true,
        end: function () {
            $('#dataList').datagrid('reload');
        }
    })
}


/**
 * 打开上传界面
 */
function openAddSrc() {
    layer.open({
        title:"流程部署",
        type:2,
        area: ['600px','300px'],
        content: flowUrl + "?type=src",
        maxmin: true,
        end: function () {
            $('#dataList').datagrid('reload');
        }
    })
}



/**
 * Created by zhuyongjie on 2017/10/20.
 */

/**
 * datagrid大小自适应浏览器大小
 */
function autoResizeDataGrid(targetId,ratio){
    $(window).resize(function () {
        $('#'+targetId).datagrid('resize', {
            width: $(window).width() * ratio,
            height: $(window).height() - 20
        });
    });
}

/**
 * 调整大小
 */
function resizeDataGridSize(targetId,ratio) {
    $('#'+targetId).datagrid('resize', {
        width: $(window).width() * ratio,
        height: $(window).height() - 20
    });
}

var columns = [
    {
        field: "taskName",
        title: "节点名称",
        align: "center",
        halign: "center",
        sortable: false,
        resizable: true,
        width: 120
    },
    {
        field: "taskKey",
        title: "节点编码",
        align: "center",
        halign: "center",
        sortable: false,
        resizable: true,
        width: 100
    },
    {
        field: "taskVariables",
        title: "节点定义参数",
        align: "left",
        halign: "center",
        sortable: false,
        resizable: true,
        width: 120
    }, {
        field: "taskControlVar",
        title: "节点控制变量",
        align: "center",
        halign: "center",
        sortable: false,
        resizable: true,
        width: 100
    },
    {
        field: "controlStr",
        title: "控制变量字符串",
        align: "center",
        halign: "center",
        sortable: false,
        resizable: true,
        width: 150
    },
    {
        field: "orderNo",
        title: "序号",
        align: "center",
        halign: "center",
        sortable: false,
        resizable: true,
        width: 50
    },
    {
        field: "stateName",
        title: "节点状态名称",
        align: "center",
        halign: "center",
        sortable: false,
        resizable: true,
        width: 120
    },
    {
        field: "candidatName",
        title: "参与者",
        align: "center",
        halign: "center",
        sortable: false,
        resizable: true,
        width: 300
    },
    {
        field: "processKey",
        title: "流程Key",
        align: "center",
        halign: "center",
        sortable: false,
        resizable: true,
        width: 250
    }
];
